<template>
  <t-dialog
    header="选择经纬度"
    :visible.sync="visible"
    width="70%"
    placement="center"
    :confirmOnEnter="true"
    :onClose="close"
    :destroyOnClose="true"
    :close-on-overlay-click="false"
  >
    <template #closeBtn>
      <icon-font name="close" size="28px" style="color:#000;" />
    </template>
    <div class="flex pb16">
      <div class="lng-lat"><span style="font-weight: bold">当前经纬度：</span>{{ location.lng }}，{{ location.lat }}</div>
      <div class="lng-lat"><span style="font-weight: bold">当前地址信息：</span>{{ location.address }}</div>
    </div>
    <div class="map-container">
      <div class="left-form">
        <t-form :data="formData" ref="form" class="mb12" label-width="auto">
          <t-form-item>
            <t-input v-model="formData.keyword" @enter="handleSearch" clearable placeholder="请输入搜索关键字"></t-input>
          </t-form-item>
        </t-form>
        <div id="panel"></div>
      </div>
      <div id="container"></div>
    </div>
    <div class="footer-height"></div>
    <template #footer>
      <div class="verify-footer">
        <!--<div class="lng-lat">当前经纬度：<span style="font-weight: bold">{{ location.lng }}，{{ location.lat }}</span></div>-->
        <div>
          <t-button class="cancel-btn" variant="outline" @click="close">
            <p class="btn-text">取消</p>
          </t-button>
          <t-button class="confirm-btn flex-1" @click="confirm">
            <p class="btn-text">确认保存</p>
          </t-button>
        </div>
      </div>
    </template>
  </t-dialog>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'
import { IconFont } from 'tdesign-icons-vue';

window._AMapSecurityConfig = {
  securityJsCode: '3efd1abdc7feb939e4e0569dab65e0f5'
}
export default {
  components: { IconFont },
  data() {
    return {
      map: null,
      visible: false,
      location: {
        lng: 106.593704,  // 经度
        lat: 29.573951, //  纬度
        address: '',
        formattedAddress: '',
      },
      center: [106.593704, 29.573951],
      auto: null,
      userInput: '',
      inputId: 'searchInput',
      placeSearch: null,
      searchPlaceInput: '',
      formData: {
        keyword: '', // 搜索关键字
      },

      autoOptions: {
        input: '',
        output: 'searchRes',
        closeResultOnScroll: false,
      },

      searchOptions: {
        pageSize: 5, // 单页显示结果条数
        pageIndex: 1, // 页码
        panel: "panel", // 结果列表将在此容器中进行展示。
        autoFitView: true, // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
      },

      locationOptions: {
        showButton: true,// 是否显示定位按钮
        position: 'LB',// 定位按钮的位置
        offset: [10, 30],// 定位按钮距离对应角落的距离
        showMarker: true,// 是否显示定位点
        showCircle: true,// 是否显示定位精度圈
        circleOptions: {// 定位精度圈的样式
          strokeColor: '#0093FF',
          noSelect: true,
          strokeOpacity: 0.5,
          strokeWeight: 1,
          fillColor: '#02B0FF',
          fillOpacity: 0.25
        }
      }
    }
  },
  mounted() {
    // DOM初始化完成进行地图初始化
    // this.initMap()
  },
  methods: {
    handleSearch() {
      this.placeSearch.search(this.formData.keyword, (status, result) => {
        console.log('result', result)
      })
    },
    confirm() {
      this.$emit('change', this.location)
      this.close()
    },
    initMap() {
      AMapLoader.load({
        key: "c561b2ff6f26958b5ed4c19138001f6d", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0",      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.Geocoder', 'AMap.Geolocation', 'AMap.PlaceSearch'],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then((AMap) => {
        // 初始化地图
        this.map = new AMap.Map("container", {  // 设置地图容器id
          viewMode: "3D",    // 是否为3D地图模式
          zoom: 10,           // 初始化地图级别
          center: [106.593704, 29.573951], // 初始化地图中心点位置
        });
        // 添加控件
        this.map.addControl(new AMap.Geolocation(this.locationOptions))

        // 添加搜索框
        this.placeSearch = new AMap.PlaceSearch({
          ...this.searchOptions,
          map: this.map,
        }) // 构造地点查询类

        // // 使用map、panel属性后，选中的POI改变时触发
        this.placeSearch.on('selectChanged', (e)=> {
          this.selectChanged(e, AMap)
        })

        // 监听点击时间
        this.map.on('click', (e)=> {
          this.handleMapClick(e, AMap)
        });

        // 添加标注
        this.addMarker(this.location, AMap)
        // 获取详细地址
        this.getAddress(this.location, AMap)
      }).catch(e => {
        console.log(e);
      })
    },
    // 选中 POI
    selectChanged(e, AMap) {
      this.getAddress(e.selected.data.location, AMap)
    },
    // 点击地图，获取经纬度，添加标注，获取详细地址
    handleMapClick(e, AMap) {
      // 添加标注
      this.addMarker(e.lnglat, AMap)

      // 获取详细地址
      this.getAddress(e.lnglat, AMap)
    },
    // 添加标注
    addMarker(lnglat, AMap) {
      if (this.marker) {
        this.map.remove(this.marker);
      }
      this.marker = new AMap.Marker({
        position: new AMap.LngLat(lnglat.lng, lnglat.lat),
        offset: new AMap.Pixel(-10, -10),
        icon: '//vdata.amap.com/icons/b18/1/2.png', // 添加 Icon 图标 URL
      });
      this.map.add(this.marker);
    },

    // 根据经纬度获取详细地址
    getAddress(lnglat, AMap) {
      this.location = {
        lng: lnglat.lng,
        lat: lnglat.lat
      }
      const geocoder = new AMap.Geocoder({});
      geocoder.getAddress(lnglat, (status, result) => {
        // console.log('result', result)
        if (status === 'complete' && result.info === 'OK') {
          // 获取详细地址信息
          const { township } = result.regeocode.addressComponent
          const address = result.regeocode.formattedAddress;
          const index = address.indexOf(township)
          let formattedAddress = ''

          if (index !== -1) {
            formattedAddress = address.substring(index, address.length)
          }

          this.location.address = address
          this.location.formattedAddress = formattedAddress
          this.$forceUpdate()
        } else {
          this.$message.error('根据经纬度查询地址失败')
          // 处理错误
          console.error('逆地理编码失败');
        }
      });
    },
    open(center) {
      this.visible = true
      this.center = center || this.center
      this.location.lng = center.lng || this.location.lng
      this.location.lat = center.lat || this.location.lat

      this.initMap()
    },
    close() {
      this.visible = false
    }
  }
}
</script>
<style>
a {
  color: black;
}
</style>

<style scoped lang="less">
.map-container {
  position: relative;
}

.left-form{
  position: absolute;
  top: 24px;
  right: 24px;
  width: 360px;
  z-index: 999;
}
#container {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 500px;
  border-radius: 8px;
}

/deep/ .t-dialog__header-content{
  font-size: 24px;
}

/deep/ .t-dialog__body{
  overflow: auto;
  padding-left: var(--td-comp-paddingLR-xxs);
  padding-right: var(--td-comp-paddingLR-xxs);
}

/deep/ t-dialog__footer {
  position: relative;
}

.btn-text{
  font-size: var(--td-size-6);
  line-height: var(--td-size-8);
}

.cancel-btn {
  width: 100px;
  height: 38px;
}

.confirm-btn{
  width: 160px;
  height: 40px;
}

.lng-lat {
  color: black;
  padding-right: var(--td-comp-paddingLR-xl);
}

.footer-height {
  height: calc(72px - var(--td-comp-paddingTB-xxl));
}
.verify-footer {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  background-color: #F6F6F6;
  border-bottom-left-radius: var(--td-radius-large);
  border-bottom-right-radius: var(--td-radius-large);
  padding: var(--td-comp-paddingTB-l) var(--td-comp-paddingLR-xxl) var(--td-comp-paddingTB-l);
}
</style>
